package com.oweight.com2tpc.connect.tcp;

import com.oweight.com2tpc.Controller;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;

@Slf4j
public class TCPClient {

    public static Channel channel;

    private static boolean reconnection = false;

    public static void start(Controller controller) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        Bootstrap b = new Bootstrap();
        b.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new ByteArrayEncoder(),
                                new ByteArrayDecoder(),
                                new TCPDataHandler(controller));
                    }
                });

        try {
            ChannelFuture f = b.connect(Controller.hostStr, Integer.parseInt(Controller.portStr)).sync();
            if (f.isSuccess()) {
                log.info("Open port: " + Controller.portStr);
                log.info("Connected success.");
                Controller.connectionSucceeded(controller.tcpStatus, controller.tcpConnect);
                reconnection = false;
            }
            channel = f.channel();
            channel.closeFuture().sync();

        } catch (InterruptedException e) {
            log.info("Connected failed!", e);
            reconnection = true;

        } finally {
            log.info("Closing");
            bossGroup.shutdownGracefully();
            Controller.connectionFailed(controller.tcpStatus, null);

            // 自动连接
            Executors.newSingleThreadExecutor().execute(() -> {
                do {
                    if (Controller.tcpInitiativeDisconnect) {
                        // 用户自行断开连接
                        break;
                    }

                    log.info("自动重连...");
                    try {
                        TCPClient.start(controller);
                    } catch (Exception e) {
                        log.error("TCP/IP断开连接！");
                    }
                } while (reconnection);
            });
        }
    }


    public static void stop() {
        if (channel != null) {
            channel.close();
        }
    }
}
